<template>
  <div class="app-container">
    <el-form
      ref="form"
      :inline="true"
      :model="formData"
      class="demo-form-inline"
    >
      <el-form-item>
        <el-input
          style="width: 250px"
          v-model="formData.orderNo"
          placeholder="请输入订单号"
        />
      </el-form-item>

      <el-form-item>
        <el-input
          style="width: 250px"
          v-model="formData.customPhone"
          placeholder="请输入手机号"
        />
      </el-form-item>

      <el-form-item>
        <el-input
          style="width: 250px"
          v-model="formData.mtSerialNumbers"
          placeholder="三方卷码号"
        />
      </el-form-item>

      <el-form-item>
        <el-select
          clearable
          v-model="formData.comeFrom"
          placeholder="请选择平台"
          @change="handleChange"
        >
          <el-option
            v-for="item in orderComeFromList"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

       <el-form-item>
         <el-tooltip class="item" effect="dark" content="若显示无数据请选择其它平台，例如抖音平台" placement="top">
        <el-select
          clearable
          v-model="formData.brandId"
          placeholder="请选择品牌"
        >
          <el-option
            v-for="item in brandList"
            :label="item.brandName"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
        
      </el-tooltip>
      </el-form-item>


         <el-form-item>
        <el-select
          clearable
          v-model="formData.factoryId"
          placeholder="请选择工厂"
        >
          <el-option
            v-for="item in factoryList"
            :label="item.factoryName"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-date-picker
          v-model="formData.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="订单开始日期"
          end-placeholder="订单结束日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-select
          clearable
          v-model="formData.status"
          placeholder="请选择订单状态"
        >
          <el-option
            v-for="item in orderStatusList"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          clearable
          v-model="formData.fulfillStatus"
          placeholder="请选择美团订单状态"
        >
          <el-option
            v-for="item in mtOrderStatusList"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          clearable
          v-model="formData.settlementStatus"
          placeholder="请选择结算状态"
        >
          <el-option
            v-for="item in settlementStatusList"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select clearable v-model="formData.shopId" placeholder="请选择店铺">
          <el-option
            v-for="item in shopList"
            :label="item.shopName"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
        <el-button class="create" type="primary" @click="create" v-if="jindianflag"
          >进店洗</el-button
        >
      </el-form-item>
    </el-form>

    <el-tabs
      v-model="queryParams.status"
      style="margin-bottom: 20px"
      @tab-click="handleTabClick"
    >
      <el-tab-pane
        :label="`全部（${orderStatistics.ALL || 0}）`"
        name="-2"
      ></el-tab-pane>
      <el-tab-pane
        :label="`待付款（${orderStatistics.PRE_PAY || 0}）`"
        name="-1"
      ></el-tab-pane>
      <el-tab-pane
        :label="`取鞋中（${orderStatistics.PICK_UP_SHOES || 0}）`"
        name="1"
      ></el-tab-pane>
      <el-tab-pane
        :label="`待入库（${orderStatistics.PENDING_STORAGE || 0}）`"
        name="2"
      ></el-tab-pane>
      <el-tab-pane
        :label="`清洗中（${orderStatistics.CLEANING_IN_PROCESS || 0}）`"
        name="3"
      ></el-tab-pane>
      <el-tab-pane
        :label="`待质检${orderStatistics.WAIT_FOR_QUALITY || 0}）`"
        name="7"
      ></el-tab-pane>
      <el-tab-pane
        :label="`待出库（${orderStatistics.PENDING_OUTBOUND || 0}）`"
        name="4"
      ></el-tab-pane>
      <el-tab-pane
        :label="`送鞋中（${orderStatistics.SENDING_SHOES || 0}）`"
        name="5"
      ></el-tab-pane>
      <el-tab-pane
        :label="`已完成（${orderStatistics.COMPLETED || 0}）`"
        name="6"
      ></el-tab-pane>
      <el-tab-pane
        :label="`已取消（${orderStatistics.CANCEL || 0}）`"
        name="0"
      ></el-tab-pane>
    </el-tabs>

    <el-table v-loading="dataLoading" :data="list" style="width: 100%">
      <el-table-column prop="orderNo" label="订单号" width="200" fixed="left">
      </el-table-column>
      <el-table-column
        prop="customPhone"
        label="手机号码"
        width="120"
        fixed="left"
      >
      </el-table-column>
      <el-table-column label="渠道">
        <template slot-scope="scope">
          <el-tag type="success">{{
            orderComeFromMap[scope.row.comeFrom]
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="mtSerialNumbers" label="三方券码号" width="120">
      </el-table-column>
      <el-table-column prop="totalPrice" label="订单金额" width="150">
        <template slot-scope="scope">
          {{ Number(scope.row.totalPrice).toFixed(2) }}（元）
        </template>
      </el-table-column>
      <el-table-column prop="" label="门店名称" width="150">
        <template slot-scope="scope">
          {{ shopListMap[scope.row.shopId]? shopListMap[scope.row.shopId].shopName:noFactory }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态">
        <template slot-scope="scope">
          <el-tag
            size="small"
            :type="scope.row.status === 0 ? 'danger' : 'success'"
            >{{ orderStatusMap[scope.row.status] }}</el-tag
          >
        </template>
      </el-table-column>

      <el-table-column prop="status" label="三方订单状态" width="150">
        <template slot-scope="scope">
          {{
            scope.row.comeFrom == 3
              ? tikTokOrderStatus[scope.row.fulfillStatus]
              : mtOrderStatus[scope.row.fulfillStatus] || "-"
          }}
        </template>
      </el-table-column>

      <el-table-column prop="settlementStatus" label="抖音预约状态" width="150">
        <template slot-scope="scope">
          {{ dyOrderStatus[scope.row.dyBookCode] || "-" }}
        </template>
      </el-table-column>

      <el-table-column label="商品信息" prop="orderGoodsNames" width="150">
        <!-- <template slot-scope="scope">
          <div v-for="item in scope.row.orderGoodPoList">
            {{ productListMap[item.goodsId].name }}[{{
              productListMap[item.goodsId].price
            }}][{{ item.buyNum }}份]
          </div>
        </template> -->
      </el-table-column>

      <el-table-column prop="washFactory" label="清洗工厂" width="180">
      </el-table-column>

      <el-table-column prop="createTime" label="下单时间" width="180">
      </el-table-column>

      <!-- <el-table-column prop="settlementStatus" label="结算状态">
        <template slot-scope="scope">
          {{ settlementStatusMap[scope.row.settlementStatus] || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="settlementPrice"
        label="结算金额（元）"
        width="120"
      >
        <template slot-scope="scope">
          {{ scope.row.settlementPrice ? scope.row.settlementPrice : "" }}
        </template>
      </el-table-column>
      <el-table-column prop="settlementTime" label="结算时间">
      </el-table-column> -->

      <el-table-column label="操作" width="360px" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="detail(scope.row.id)"
            >详情</el-button
          >

          <el-button
            :loading="printLoading === scope.row.id"
            type="primary"
            size="mini"
            @click="print(scope.row)"
            >打印小票</el-button
          >

          <el-popconfirm
            v-if="scope.row.comeFrom === '2'"
            style="margin-left: 10px;margin-top: 10px;"
            title="您确认已完成美团订单吗？"
            @confirm="mtComplete(scope.row.id)"
          >
            <el-button slot="reference" type="primary" size="mini"
              >美团完成</el-button
            >
          </el-popconfirm>

          <el-button
            type="primary"
            size="mini"
            style="margin-left: 10px;margin-top: 10px;"
            v-if="scope.row.status > 4"
            @click="backWash(scope.row.id)"
            >返洗</el-button>

           <el-button
            type="primary"
            size="mini"
            :disabled="scope.row.hasWorkOrder==0"
            style="margin-left: 10px; margin-top: 10px;"
            @click="createWorkOrder(scope.row)"
            >创建工单</el-button>

          <template v-if="scope.row.comeFrom === '1' && scope.row.status === 2">
            <el-popconfirm
              style="margin-left: 10px;margin-top: 10px;"
              title="您确定要取消订单吗？"
              @confirm="cancelOrder(scope.row.id)"
            >
              <el-button slot="reference" type="primary" size="mini"
                >取消订单</el-button
              >
            </el-popconfirm>
          </template>

          <template
            v-if="
              scope.row.comeFrom === '4' &&
              (scope.row.status === -1 || scope.row.status === 1)
            "
          >
            <el-popconfirm
              style="margin-left: 10px;"
              title="您确定要取消订单吗？"
              @confirm="cancelOrderByMini(scope.row.id)"
            >
              <el-button slot="reference" type="primary" size="mini"
                >取消订单</el-button
              >
            </el-popconfirm>
          </template>

          <template v-if="scope.row.comeFrom === '2' && scope.row.status === 1">
            <el-popconfirm
              style="margin-left: 10px"
              title="您确定要取消订单吗？"
              @confirm="cancelOrderByMt(scope.row.id)"
            >
              <el-button slot="reference" type="primary" size="mini"
                >取消订单</el-button
              >
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="queryParams.total > 0"
      :total="queryParams.total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getListData"
    />

    <OrderDetail
      :drawerVisible="drawerVisible"
      :detailId="detailId"
      :productListMap="productListMap"
      @close="drawerVisible = false"
      @printReceipt="printReceiptByDetail"
    />

    <BackWash
      :backWashVisible="backWashVisible"
      :detailId="detailId"
      :productListMap="productListMap"
      @close="backWashVisible = false"
      @toDetail="backToDetail"
    />

    <PrintOrderReceipt
      :detail="printOrderReceiptObject.detail"
      :shopName="printOrderReceiptObject.shopName"
      :id="printOrderReceiptObject.id"
      :productListMap="productListMap"
      ref="PrintOrderReceipt"
    />
    <createAndUpdateWorkOrder
    :showWorkOrder="showWorkOrder"
    :shopListMap="shopListMap"
     :rollBackFn="getListDataFn"
    @cancel-workOrder-click="cancelWorkOrder"
     :details="details">
    </createAndUpdateWorkOrder>
  </div>
</template>

<script>
import {
  getOrderList,
  getOrderStatistics,
  cancelOrder,
  getOrderDetail,
  cancelMeituanOrder,
  cancelOrderByMini,
  meituanOrderFinish,
} from "@/api/order/index";
import { getShopGoods } from "@/api/product";
import {
  orderComeFromMap,
  productFormTypeListDic,
  orderComeFromList,
  orderStatusMap,
  orderStatusList,
  settlementStatusMap,
  settlementStatusList,
  tikTokOrderStatus,
  mtOrderStatus,
  mtOrderStatusList,
  dyOrderStatus,
} from "@/config";
import OrderDetail from "./components/detail";
import createAndUpdateWorkOrder from "./components/createAndUpdateWorkOrder.vue";
import { getShopList } from "@/api/shop/index";
import BackWash from "./components/backWash.vue";
import { setStartOfDay, setEndOfDay } from "@/utils/tool";
import PrintOrderReceipt from "@/components/PrintOrderReceipt/PrintOrderReceipt.vue";
import { getBrandByChannel } from '@/api/brand/index'
import { listFactory } from '@/api/factory/index'
export default {
  name: "Index",
  components: {
    OrderDetail,
    BackWash,
    PrintOrderReceipt,
    createAndUpdateWorkOrder
  },
  data() {
    return {
      factoryList:[],
      brandList:[],
      dataLoading: false,
      jindianflag:true,
      dyOrderStatus,
      printLoading: "",
      queryParams: {
        page: 1,
        limit: 10,
        pageSize:10,
        total: 0,
        status: "-2",
      },
      list: [],
      orderComeFromMap,
      productFormTypeListDic,
      orderStatusMap,
      productListMap: {},
      shopList: [],
      shopListMap: {},
      showWorkOrder:false,
      orderStatistics: {},
      noFactory:"没有匹配到工厂",
      settlementStatusMap,

      formData: {
        orderNo: "",
        customPhone: "",
        comeFrom: "",
        status: "",
        dateRange: "",
        mtSerialNumbers: "",
        shopId: "",
        fulfillStatus: "",
      },
      orderComeFromList,
      orderStatusList,
      settlementStatusList,

      drawerVisible: false,
      detailId: "",

      backWashVisible: false,

      printOrderReceiptObject: {
        detail: "",
        shopName: "",
        id: "list-print",
      },

      mtOrderStatus,
      details:{},
      mtOrderStatusList,
      tikTokOrderStatus,
    };
  },
  created() {
    getShopGoods(
      {
        extendInfo: "abc",
      },
      1,
      999999
    ).then((res) => {
      let productListMap = {};
      res.data.records.forEach((item) => {
        productListMap[item.id] = item;
      });
      this.productListMap = productListMap;
    });

    getShopList({}, 1, 999999).then((res) => {
      let shopListMap = {};
      res.data.records.forEach((item) => {
        shopListMap[item.id] = item;
      });
      this.shopList = res.data.records;
      this.shopListMap = shopListMap;
    });

    this.getOrderStatistics();

    if (this.$route.query.comeFrom) {
      this.formData.comeFrom = this.$route.query.comeFrom;
      this.queryParams.comeFrom = this.$route.query.comeFrom;
    }

    if (this.$route.query.status) {
      this.formData.status = this.$route.query.status;
      this.queryParams.status = this.$route.query.status;
    }

    this.getListData({
      page: 1,
      limit: 10,
    });
  },

  mounted() {

  this.getFactoryList()

    if(!this.$store.state.user.currentShop.id){
       this.jindianflag=false
    }
    if (this.$route.query.id) {
      this.detailId = this.$route.query.id;
      this.drawerVisible = true;
    }

    window.history.replaceState({}, "", this.$route.path);
  },

  watch: {
    $route(to, from) {
      if (this.$route.query.comeFrom) {
        this.reset();
        this.formData.comeFrom = this.$route.query.comeFrom;
        this.queryParams.comeFrom = this.$route.query.comeFrom;
        this.getListData({
          page: 1,
          limit: 10,
        });
      }

      if (this.$route.query.status) {
        this.reset();
        this.formData.status = this.$route.query.status;
        this.queryParams.status = this.$route.query.status;
        this.getListData({
          page: 1,
          limit: 10,
        });
      }
    },
  },

  methods: {

    getFactoryList(){

      listFactory({pageNo:1,pageSize:999}).then(res=>{
        this.factoryList=[]
        this.factoryList=res.data.records
      })
        
    
    },

    getListDataFn(){

      this.getListData({
          page: 1,
          limit: 10,
        });
    },

    cancelWorkOrder(){
      this.showWorkOrder=false
    },
    createWorkOrder(item){
      // console.info("item",item)
      this.showWorkOrder=true
      item.orderId=item.id
      this.details=item
      // console.info(this.details)

    },


    handleChange(){
     this.brandList=[]
     let brandObj={... this.formData}
     brandObj.brandId=""
     this.formData=brandObj
     let channel=this.productFormTypeListDic[this.formData.comeFrom];
     if(channel){
        getBrandByChannel(channel).then(res=>{
          this.brandList=res.data
          // this.formData.brandId
        })
     }

     //获取品牌

    },

    // 获取统计值
    getOrderStatistics() {
      getOrderStatistics().then((res) => {
        let count = Object.keys(res.data).reduce((prev, key) => {
          return prev + res.data[key];
        }, 0);
        this.orderStatistics = {
          ...res.data,
          ALL: count,
        };
      });
    },
    async mtComplete(id) {
      await meituanOrderFinish(id);
      this.$message.success("操作成功");
    },
    getListData({ page, limit }) {
      this.showWorkOrder=false
      this.dataLoading = true;

      const params = {
        ...this.queryParams,
        status: this.queryParams.status === "-2" ? "" : this.queryParams.status,

        // 将选择的日期范围转换为开始时间和结束时间
        startTime: this.formData.dateRange
          ? setStartOfDay(this.formData.dateRange[0])
          : "",
        endTime: this.formData.dateRange
          ? setEndOfDay(this.formData.dateRange[1])
          : "",
      };
      getOrderList(params, this.queryParams.page, this.queryParams.pageSize)
        .then(({ data }) => {
          this.list = data.records;
          this.queryParams.total = data.total;
          this.queryParams.page = data.current;
          this.queryParams.limit = data.size;
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    create() {
      this.$router.push({ path: "/order/edit" });
    },
    backWash(id) {
      this.detailId = id;
      this.backWashVisible = true;
    },
    detail(id) {
      this.detailId = id;
      this.drawerVisible = true;
    },
    handleTabClick(tab, event) {
      this.queryParams.status = tab.name;
      this.formData.status = tab.name === "-2" ? "" : tab.name;
      this.getListData({
        page: 1,
        limit: 10,
      });
    },

    reset() {
      this.formData = {
        orderNo: "",
        comeFrom: "",
        status: "",
        settlementStatus: "",
        dateRange: "",
        customPhone: "",
        fulfillStatus: "",
        mtSerialNumbers: "",
        shopId: "",
      };
    },
    onSearch() {
      this.queryParams = {
        ...this.queryParams,
        ...this.formData,
        status: this.formData.status || "-2",
      };
      this.getListData({
        page: 1,
        limit: 10,
      });
    },

    cancelOrder(id) {
      cancelOrder(id).then(() => {
        this.getOrderStatistics();
        this.$message.success("取消订单成功");
        this.getListData({
          page: 1,
          limit: 10,
        });
      });
    },
    cancelOrderByMini(id) {
      cancelOrderByMini(id).then(() => {
        this.getOrderStatistics();
        this.$message.success("取消订单成功");
        this.getListData({
          page: 1,
          limit: 10,
        });
      });
    },

    cancelOrderByMt(id) {
      cancelMeituanOrder(id).then(() => {
        this.getOrderStatistics();
        this.$message.success("取消订单成功");
        this.getListData({
          page: 1,
          limit: 10,
        });
      });
    },

    // 打印小票
    print(item) {
      this.printLoading = item.id;
      getOrderDetail(item.id)
        .then((res) => {
          this.printOrderReceiptObject = {
            detail: res.data,
            shopName: this.shopListMap[item.shopId]? this.shopListMap[item.shopId].shopName:this.noFactory,
            id: "list-print",
          };
          this.$nextTick(() => {
            this.$refs.PrintOrderReceipt.$refs.printBtn.click();
          });
        })
        .finally(() => {
          this.printLoading = "";
        });
    },

    printReceiptByDetail(detail) {
      this.printOrderReceiptObject = {
        detail,
        shopName: this.shopListMap[detail.shopId]? this.shopListMap[detail.shopId].shopName:this.noFactory,
        id: "list-print",
      };
      this.$nextTick(() => {
        this.$refs.PrintOrderReceipt.$refs.printBtn.click();
      });
    },

    backToDetail(id) {
      this.backWashVisible = false;
      this.detailId = id;
      this.drawerVisible = true;
    },

    handleDrawerClose() {
      this.drawerVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.create {
  margin-bottom: 20px;
}

::v-deep .el-button--mini{
  margin-top: 10px;
}
</style>
